package com.example.imagepicker;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.lcw.library.imagepicker.data.MediaFile;

import java.util.List;

/**
 * 选择的图片适配器
 */
public class SelectedImageAdapter extends RecyclerView.Adapter<SelectedImageAdapter.ViewHolder> {

    private Context context;
    private List<MediaFile> mediaFiles;
    private GlideImageLoader imageLoader;

    public SelectedImageAdapter(Context context, List<MediaFile> mediaFiles, GlideImageLoader imageLoader) {
        this.context = context;
        this.mediaFiles = mediaFiles;
        this.imageLoader = imageLoader;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_selected_image, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MediaFile mediaFile = mediaFiles.get(position);
        
        // 智能加载图片，优先使用Uri
        if (mediaFile.isVideo()) {
            // 视频缩略图
            imageLoader.loadVideoThumbnailSmart(holder.imageView, mediaFile.getPath(), mediaFile.getUri());
            holder.typeIndicator.setVisibility(View.VISIBLE);
            holder.typeIndicator.setText("视频");
        } else {
            // 图片
            imageLoader.loadImageSmart(holder.imageView, mediaFile.getPath(), mediaFile.getUri());
            holder.typeIndicator.setVisibility(View.GONE);
        }
        
        // 删除按钮
        holder.deleteButton.setOnClickListener(v -> {
            int currentPosition = holder.getAdapterPosition();
            if (currentPosition != RecyclerView.NO_POSITION) {
                mediaFiles.remove(currentPosition);
                notifyItemRemoved(currentPosition);
                notifyItemRangeChanged(currentPosition, mediaFiles.size());
            }
        });
    }

    @Override
    public int getItemCount() {
        return mediaFiles.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView deleteButton;
        TextView typeIndicator;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.iv_image);
            deleteButton = itemView.findViewById(R.id.iv_delete);
            typeIndicator = itemView.findViewById(R.id.tv_type);
        }
    }
} 